<?php

/**
 * 通用自定义定义标签
 * 用法：
 * 1：载入
 *  <taglib name="lx" />
 * 2：调用
 * <lx:list table="member" field="name"  page="$page,$rows" >
 *    {$v.id} -- {$v.name}<br />
 * </lx:list>
 * 说明:
 * 1.可以直接在标签上面写sql属性
 * 2.限制查询条数请用 limit属性
 * 3.要数据分页请用page属性，可传2个参数，用逗号分隔，前一个参数当前页码，后一个参数每页查询几条
 * 4.显示分页请在视图页面输出 {$pageStr}
 * 5.调用模型的方法 用 method="getOne(1,2,3)" 【引号里面直接调用方法】
 */

namespace Think\Template\TagLib;

use Think\Template\TagLib;

class Lx extends TagLib
{

    protected $tags = array(
        'list' => array('attr' => 'table,order,limit,where,join,field,page,relation,method,cache,dump,sql', 'close' => 1),
    );

    public function _list($attr, $content)
    {
        $defaultAttr = explode(',', $this->tags['list']['attr']);
        $vars = array();
        foreach ($defaultAttr as $v) {
            if ($attr[$v]) {
                $vars[$v] = $attr[$v];
            }
        }
        if (!isset($vars['table']) || empty($vars['table'])) {
            return false;
        }
        //是用模型中的特定方法还是select
        if (isset($vars['method'])) {
            $select = '->' . $vars['method'];
        } else {
            $select = "->select()";
        }
        //limit and page
        $limit = '';

        if (!isset($vars['page'])) {
            if (isset($vars['limit'])) {
                $limit = '->limit("' . $vars['limit'] . '")';
            }
        } else {
            $limit = '->page("$page,$rows")';
        }
        //dump 调试
        $dump = '';
        if (isset($vars['dump']) && $vars['dump'] == "true") {
            $dump = '<?php dump($data) ?>';
        }
        //getLastSql 调试
        $lastSql = '';
        if (isset($vars['sql']) && $vars['sql'] == "true") {
            $lastSql = ' echo "<br/>" . M()->getLastSql(); ';
        }
        unset($vars['page'], $vars['limit'], $vars['method'], $vars['dump'], $vars['sql']);
        $tmpStr = '';
        $where = '';
        $join = '';
        foreach ($vars as $k => $v) {
            if ($k == 'table') {
                continue;
            }
            if ($k == 'where') {
                $where = $v;
            }
            if ($k == 'join') {
                $join = $v;
            }
            $tmpStr .= '->' . $k . '("' . $v . '")';
        }
        $str = '<?php
            $page = I("p", false) ? I("p") : I("page");
            $page = empty($page) ? 1 : $page;
            $rows = I("rows", 15);
            $table =  ' . ucfirst($vars['table']) . ';
            $data = D("$table")' . $tmpStr . $limit . $select . ';
            foreach($data as $k=>$v): ?>';
        $str .= $content;
        $str .= '<?php
             if(!is_array($v)){
                 break ;
             }
             endforeach;
             '.$lastSql.'
             $total = D("$table")->where("' . $where . '")->join("' . $join . '")->count();
             $Page = new \Think\Page($total,$rows);
             $pageStr = $Page->show();
        ?>';
        $str .= $dump;
        return $str;
    }


}
